package com.cmy.mylog.config;

import com.cmy.mylog.aop.MyLogAspect;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.stream.Collectors;

/**
 * @Author:Cmy
 * @Date:2023-11-13 13:55
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(MyLogProperties.class)
@ConditionalOnProperty(prefix = "spring.my-log", name = "enabled", havingValue = "true")
public class MyLogAutoConfiguration {


    @Resource
    private MyLogProperties myLogProperties;

    @Bean
    public Advisor loggingAspect() {
        String expression = "@annotation(com.cmy.mylog.annotations.MyLog)";
        String scanPackages = myLogProperties.getScanPackages();
        if (StringUtils.isNotBlank(scanPackages)){
            expression = expression+"||"+ Arrays
                    .stream(scanPackages.split(","))
                    .map(s -> "execution(* " + s + ".*.*(..))")
                    .collect(Collectors.joining("||"));
        }
        log.info("now the expression is : {}",expression);
        MyLogAspect myLogAspect = new MyLogAspect();
        AspectJExpressionPointcut aspectJExpressionPointcut = new AspectJExpressionPointcut();
        aspectJExpressionPointcut.setExpression(expression);
        return new DefaultPointcutAdvisor(aspectJExpressionPointcut, myLogAspect);
    }



}

    